package com.qububu.admin;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.qububu.common.user.dto.UserLoginInfoDto;
import com.qububu.common.user.dto.UserLoginInfoDto.LoginType;
import com.qububu.systemBase.exceptions.AdminException;
import com.qububu.systemBase.exceptions.SessionTimeoutException;
import com.qububu.utils.SystemConstants;

public class AdminInterceptor implements HandlerInterceptor {

	// 许访问的URL地址
	private List<String> allowUrls;

	public List<String> getAllowUrls() {
		return allowUrls;
	}

	public void setAllowUrls(List<String> allowUrls) {
		this.allowUrls = allowUrls;
	}	
	
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub
		
	}

	public boolean preHandle(HttpServletRequest req, HttpServletResponse resp,
			Object arg2) throws Exception {
		
		String requestUri = req.getRequestURI();
		for (String url : allowUrls) {
			if (requestUri.endsWith(url)) {
				return true;
			}
		}

		return isAdmin(req);
	}
	
	/**
	 * @功能 判断是否为管理员
	 * @param 
	 * @return true为管理员
	 * @throws SessionTimeoutException 
	 */
	public boolean isAdmin(HttpServletRequest req) throws AdminException{
		UserLoginInfoDto userLoginInfo = (UserLoginInfoDto) req.getSession().getAttribute(SystemConstants.USER_LOGININFO);
		if (userLoginInfo == null || userLoginInfo.getLoginType() == null) {
			String happenAtWhere = "管理员过滤器,判断是否为管理员时,没有登录想直接进入管理中心";
			throw new AdminException(happenAtWhere);
		} else {
			if (userLoginInfo.getLoginType().equals(LoginType.ADMIN_SYSTEM)) {
				return true;
			} else {
				String happenAtWhere = "管理员过滤器,判断是否为管理员时,不是管理员想进入管理中心";
				throw new AdminException(happenAtWhere);
			}
		}
		
	}
}
